<?php
/**
 * Personnel Model
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */

class Personnel extends CActiveRecord {
    /**
     * The followings are the available columns in table 'www_personnels':
     * @var integer $id
     * @var integer $node_id
     * @var string $name
     * @var integer $sex
     * @var string $birthday
     * @var string $title
     * @var string $summary
     * @var integer $status
     * @var integer $is_recommend
     * @var integer $is_picking
     * @var integer $order_pos
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{personnels}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('node_id, name, birthday, summary', 'required'),
            array('node_id, sex, status, order_pos, created, updated', 'numerical', 'integerOnly' => true),
            array('is_recommend, is_picking', 'boolean', 'trueValue' => 1, 'falseValue' => 0),
            array('name', 'length', 'max' => 60),
            array('title, picture_saved_path, thumbnail_saved_path', 'length', 'max' => 200),
            array('picture_saved_path', 'file', 'on' => 'insert',
                'allowEmpty' => false,
                'types' => 'jpg, jpeg, gif',
                'maxSize' => 1024 * 1024 * 10,
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        return array(
            'node' => array(self::BELONGS_TO, 'Node', 'node_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'node_id' => Yii::t('common', 'node_id'),
            'name' => Yii::t('personnel', 'name'),
            'sex' => Yii::t('options', 'sex'),
            'birthday' => Yii::t('personnel', 'birthday'),
            'title' => Yii::t('personnel', 'title'),
            'picture_saved_path' => Yii::t('personnel', 'picture_saved_path'),
            'summary' => Yii::t('personnel', 'summary'),
            'status' => Yii::t('options', 'status'),
            'is_recommend' => Yii::t('common', 'is_recommend'),
            'is_picking' => Yii::t('common', 'is_picking'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    public function getAges() {
        return 1;
    }

    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    public function getSexTextFormat() {
        $options = Options::sexOptions();
        return (isset($options[$this->sex])) ? $options[$this->sex] : 'unknown';
    }

    // "status" field Icon format
    public function getStatusIconFormat() {
        switch ($this->status) {
            case Options::STATUS_DRAFT:
                $img = 'status_draft.gif';
                break;
            case Options::STATUS_PUBLISHED:
                $img = 'status_published.gif';
                break;
            case Options::STATUS_PENDING_DELETE:
                $img = 'status_pending_delete.gif';
                break;
            default:
                $img = 'status_unknown.gif';
        }
        return CHtml::image(Yii::app()->assetManager->baseUrl . '/backend/images/' . $img);
    }

    // status AJax submit
    public function getStatusAjaxFormat() {
        return CHtml::ajaxLink($this->statusIconFormat,
            Yii::app()->createUrl('backend/personnels/changeStatus'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#status{$this->id}",
            ),
            array('id' => "status{$this->id}")
        );
    }

    // “是否推荐”图标格式
    public function getIsRecommendIconFormat() {
        $img = (intval($this->is_recommend) == Options::RECOMMEND_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . '/assets/backend/images/' . $img);
    }

    // change recommend status ajax link
    public function getIsRecommendAjaxLink() {
        return CHtml::ajaxLink($this->isRecommendIconFormat,
            Yii::app()->createUrl('backend/personnels/changeRecommend'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#recommend{$this->id}",
            ),
            array('id' => "recommend{$this->id}")
        );
    }

    // “是否精品”图标格式
    public function getIsPickingIconFormat() {
        $img = (intval($this->is_picking) == Options::PICKING_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . "/assets/backend/images/{$img}");
    }

    // change picking status ajax link
    public function getIsPickingAjaxLink() {
        return CHtml::ajaxLink($this->isPickingIconFormat,
            Yii::app()->createUrl('/backend/personnels/changePicking'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#picking{$this->id}",
            ),
            array('id' => "picking{$this->id}")
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    private $_original_picture_saved_path;
    public function afterFind() {
        $this->_original_picture_saved_path = $this->picture_saved_path;
    }

    public function beforeSave() {
        parent::beforeSave();
        $uploading_file = CUploadedFile::getInstance($this, 'picture_saved_path');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                $model = Personnel::model()->findByPk($this->id);
                @unlink($model->picturePath);
                @unlink($model->thumbnailPath);
            }
            $filename = md5(time() . $this->node_id) . '.' . $uploading_file->getExtensionName();
            $this->picture_saved_path = $filename;
            $this->_original_picture_saved_path = $filename;
            $uploading_file->saveAs(YHtml::uploadPath('personnel/', true) . $filename);

            Yii::import('application.extensions.AppHelper.YImage');
            $this->thumbnail_saved_path = YImage::generateThumbnail("personnel", $filename);
        } else {
            $this->picture_saved_path = $this->_original_picture_saved_path;
        }

        return true;
    }

    public function afterDelete() {
        @unlink($this->picturePath);
        @unlink($this->thumbnailPath);
    }

    // get picture saved path
    public function getPicturePath() {
        return YHtml::uploadPath("personnel/{$this->picture_saved_path}");
    }

    // get picture file source
    public function getPictureSource() {
        return YHtml::mediaUrl("personnel/{$this->picture_saved_path}");
    }

    // get thumbnail saved path
    public function getThumbnailPath() {
        return YHtml::uploadPath("personnel/{$this->thumbnail_saved_path}");
    }

    // get picture file source
    public function getThumbnailSource() {
        return YHtml::mediaUrl("personnel/{$this->thumbnail_saved_path}");
    }

    protected function findBase($type = 'recent', $node = null, $limit = 12) {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status = ' . Options::STATUS_PUBLISHED;
        if ($node !== null) {
            if (is_array($node)) {
                $criteria->addInCondition('node_id', $node);
            } else if (is_int($node)) {
                $criteria->addCondition("node_id = {$node}");
            }
        }
        switch (trim($type)) {
            case 'recent':
                $criteria->order = 'created DESC';
                break;
            case 'recommend':
                $criteria->addCondition('is_recommend = ' . Options::RECOMMEND_YES);
                break;
            case 'picking':
                $criteria->addCondition('is_picking = ' . Options::PICKING_YES);
                break;
        }
        return self::model()->findAll($criteria);
    }
    /**
     * 获取最近新增记录
     * @param <integer> $node
     * @param <integer> $limit
     * @return array
     */
    public function findRecent($node = null, $limit = 12) {
        return $this->findBase('recent', $node, $limit);
    }

    // 推荐记录
    public function findRecommend($node = null, $limit = 12) {
        return $this->findBase('recommend', $node, $limit);
    }

    // 置顶记录
    public function findPicking($node = null, $limit = 12) {
        return $this->findBase('picking', $node, $limit);
    }
}